import {useTableActionRedux} from "@/components/ant-ext-table/redux/HAdminContext";
import SysRole, {SysRoleEntity} from "@/api/sys-role";
import {useActionTitle, useEdit} from "@/common/hooks";
import HModal from "@/components/ant-ext/HModal";
import {HSearchTree} from "@/components/ant-ext/HSearchTree";
import {SysMenuTree} from "@/api/sys-menu";
import {Key, useEffect, useState} from "react";


export default function RoleMenu() {
    const {action, reset} = useTableActionRedux<SysRoleEntity>()
    const {title} = useActionTitle(action, SysRole.ROLE_MENU_MAPPING)
    const [menuTree, setMenuTree] = useState<SysMenuTree[]>([])
    const [checkedKeys, setCheckedKeys] = useState<Key[]>([])
    const [refreshExpandedKeys, setRefreshExpandedKeys] = useState<Key[]>([])
    const close = () => {
        reset()
    }
    useEffect(() => {
        if (action.match(SysRole.ROLE_MENU)) {
            SysRole.selectRoleMenu({
                params: {code: action.getRow()?.roleCode}, success: (data) => {
                    setMenuTree(data.list)
                    setCheckedKeys(data.selected)
                    setRefreshExpandedKeys(data.list.map(p => p.key))
                }
            })
        }
    }, [action])

    const doSubmit = useEdit(SysRole.doEditRoleMenu, {
        success: () => {
            close()
        }
    })


    return <HModal onCancel={close} type={"setUp"} style={{width: "400px", height: "200px"}}
                   onOk={() => doSubmit({body: {code: action.getRow()?.roleCode, selected: checkedKeys}})}
                   visible={title !== undefined}
                   title={title}
    >
        <HSearchTree checkable={true} refreshExpandedKeys={refreshExpandedKeys} checkedKeys={checkedKeys}
                     checkStrictly
                     onCheck={(keys) => {
                         console.log(keys)
                         // @ts-ignore
                         setCheckedKeys(keys.checked)
                     }} showIcon={true}
                     showLine={true} treeData={menuTree}/>
    </HModal>
}